package com.foreknow.controller;

import com.foreknow.model.Guestbook;
import com.foreknow.service.GuestbookService;
import com.foreknow.service.impl.GuestbookServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

public class AddMessageServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置服务器向客户端响应的内容的类型（MIME）
        resp.setContentType("text/html;charset=utf-8");
        //设置客户端向服务器端请求的字符编码集为utf-8
        req.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();
        //获取请求参数
        String name = req.getParameter("name");
        String phone = req.getParameter("phone");
        String email = req.getParameter("email");
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        //调用Service层的方法
        GuestbookService service = new GuestbookServiceImpl();
        Guestbook guestbook = new Guestbook();
        guestbook.setName(name);
        guestbook.setPhone(phone);
        guestbook.setEmail(email);
        guestbook.setTitle(title);
        guestbook.setContent(content);
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        guestbook.setCreatedtime(simpleDateFormat.format(date));
        boolean isRight = service.add(guestbook);
        if(isRight) {
            //out.println("<a href='get'>query all message</a>");
            //通过请求转发跳转资源
            req.getRequestDispatcher("get").forward(req,resp);
            //通过重定向跳转资源
            //resp.sendRedirect("http://www.163.com");


        }else {
            out.println("error......");
        }

    }
}
